package com.atguigu.tingshu.user.api;

import com.atguigu.tingshu.common.execption.GuiguException;
import com.atguigu.tingshu.common.login.annotation.TingshuLogin;
import com.atguigu.tingshu.common.result.Result;
import com.atguigu.tingshu.common.result.ResultCodeEnum;
import com.atguigu.tingshu.common.util.AuthContextHolder;
import com.atguigu.tingshu.model.user.UserInfo;
import com.atguigu.tingshu.user.service.UserInfoService;
import com.atguigu.tingshu.vo.user.UserInfoVo;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Map;

//http://localhost:8500/api/user/wxLogin/wxLogin/0b3y7O0006q6qU1yd4400fmsHx4y7O0M
@Tag(name = "微信授权登录接口")
@RestController
@RequestMapping("/api/user/wxLogin")
@Slf4j
public class WxLoginApiController {
    @Autowired
    private UserInfoService userInfoService;
    @GetMapping("/wxLogin/{code}")
    public Result wxLogin(@PathVariable(value = "code") String code) {
        Map<String,Object> map =userInfoService.wxLogin(code);
        return Result.ok(map);
    }



    // http://localhost:8500/api/user/wxLogin/getUserInfo
    @TingshuLogin
    @GetMapping("/getUserInfo")
    public Result userInfo() {
        //从ThreadLocal中获取userid
        Long userId = AuthContextHolder.getUserId();
        UserInfo userInfo = userInfoService.getById(userId);
        if (userInfo == null) {
            throw new GuiguException(201, "用户不存在");
        }
        UserInfoVo userInfoVo = new UserInfoVo();
        BeanUtils.copyProperties(userInfo,userInfoVo);
        return Result.ok(userInfoVo);
    }


    // http://localhost:8500/api/user/wxLogin/getUserInfo
    @GetMapping("/getUserInfo/getNewToken")
    @Operation(summary = "获取新令牌")
    @TingshuLogin
    public Result getNewAccessToken() {
       Map<String,Object> map =  userInfoService.getNewRefreshToken();
        String flsg = (String) map.get("1");
        if (map == null && StringUtils.isEmpty(flsg)) {
            return Result.build(null, ResultCodeEnum.LOGIN_AUTH);
        }
        return Result.ok(map);
    }

}